// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.DataIndex;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearchFilter;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.LogisticsChannel;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.LogisticsChannelFreightMapper;
import com.fowo.api.mapper.LogisticsChannelMapper;
import com.fowo.api.mapper.LogisticsChannelOtherFeesMapper;
import com.fowo.api.mapper.LogisticsProviderMapper;
import com.fowo.api.mapper.SysCountryMapper;
import com.fowo.api.model.logistics.channel.LogisticsChannelExcelPo;
import com.fowo.api.model.logistics.channel.LogisticsChannelImportPo;
import com.fowo.api.model.logistics.channel.LogisticsChannelItemVo;
import com.fowo.api.model.logistics.channel.LogisticsChannelSearchParamPo;
import com.fowo.api.model.logistics.channel.LogisticsChannelVo;
import com.fowo.api.model.logistics.channel.constant.LogisticsChannelBllingRulesEnums;
import com.fowo.api.model.logistics.channel.constant.LogisticsChannelModeShippingEnums;
import com.fowo.api.model.logistics.channel.constant.LogisticsChannelSplitCalculationEnums;
import com.fowo.api.model.logistics.channel.constant.LogisticsChannelStateEnums;
import com.fowo.api.model.logistics.channel.constant.LogisticsChannelTaxIncludedEnums;
import com.fowo.api.model.logistics.channel.freight.LogisticsChannelFreightSearchParamPo;
import com.fowo.api.model.logistics.channel.other.fees.LogisticsChannelOtherFeesSearchParamPo;
import com.fowo.api.model.logistics.provider.LogisticsProviderItemVo;
import com.fowo.api.model.logistics.provider.LogisticsProviderSearchParamPo;
import com.fowo.api.model.sys.country.SysCountryItemVo;
import com.fowo.api.model.sys.country.SysCountrySearchParamPo;
import com.fowo.api.service.LogisticsChannelFreightService;
import com.fowo.api.service.LogisticsChannelOtherFeesService;
import com.fowo.api.service.LogisticsChannelService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysArea;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysAreaMapper;
import com.fowo.api.sys.model.SysAreaSearchParamPo;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 物流渠道 服务实现基类
 * @author 蜂窝蜜造平台 配置人：王阳阳，沈友谅
 */
@Slf4j
@DataObjectType(LogisticsChannel.class)
@DS("ds24")
public class LogisticsChannelBaseServiceImpl
  extends ServiceImpl<LogisticsChannelMapper, LogisticsChannel>
  implements LogisticsChannelService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("channelNameName", "lp.`name`");
      put("destinationCountryCountry", "sc.`country`");
      put("deliveryAddressName", "sa.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected LogisticsChannelService self;

  @Resource
  protected LogisticsChannelFreightService logisticsChannelFreightService;

  @Resource
  protected LogisticsChannelOtherFeesService logisticsChannelOtherFeesService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected LogisticsProviderMapper logisticsProviderMapper;

  @Resource
  protected SysCountryMapper sysCountryMapper;

  @Resource
  protected SysAreaMapper sysAreaMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建物流渠道
   * @param model 物流渠道
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(LogisticsChannelVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LogisticsChannel entity = new LogisticsChannel();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getState() == null) {
      entity.setState("0");
    }

    if (model.getBllingRules() == null) {
      entity.setBllingRules("0");
    }

    if (model.getSplitCalculation() == null) {
      entity.setSplitCalculation("1");
    }

    if (model.getBillingRules() == null) {
      entity.setBillingRules("0");
    }

    if (model.getSplitCalc() == null) {
      entity.setSplitCalc("0");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("物流渠道保存失败");
  }

  /**
   * 更新所有子表
   * @param model 物流渠道
   */
  protected void updateAllChilds(LogisticsChannelVo model) throws Exception {
    if (model.getFreightRules() != null) {
      logisticsChannelFreightService.saveAllByParentLogisticsChannel(
        model.getId(),
        model.getFreightRules()
      );
    }

    if (model.getOtherExpenses() != null) {
      logisticsChannelOtherFeesService.saveAllByParentLogisticsChannel(
        model.getId(),
        model.getOtherExpenses()
      );
    }
  }

  /**
   * 更新物流渠道
   * @param model 物流渠道
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(LogisticsChannelVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LogisticsChannel entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("物流渠道不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新物流渠道（带空值）
   * @param model 物流渠道
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(LogisticsChannelVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LogisticsChannel entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("物流渠道不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(LogisticsChannel::getName, model.getName())
      .set(LogisticsChannel::getChannelName, model.getChannelName())
      .set(LogisticsChannel::getExpectAgeing, model.getExpectAgeing())
      .set(LogisticsChannel::getLastUpdateTime, model.getLastUpdateTime())
      .set(LogisticsChannel::getLastUpdateUser, model.getLastUpdateUser())
      .set(LogisticsChannel::getZipCode, model.getZipCode())
      .set(LogisticsChannel::getModeShipping, model.getModeShipping())
      .set(
        model.getDestinationCountry() != null,
        LogisticsChannel::getDestinationCountry,
        JSON.toJSONString(model.getDestinationCountry())
      )
      .setSql(
        model.getDestinationCountry() == null,
        "destination_country = null"
      )
      .set(LogisticsChannel::getDeliveryAddress, model.getDeliveryAddress())
      .set(LogisticsChannel::getTaxIncluded, model.getTaxIncluded())
      .set(LogisticsChannel::getState, model.getState())
      .set(LogisticsChannel::getRemarks, model.getRemarks())
      .set(LogisticsChannel::getBllingRules, model.getBllingRules())
      .set(LogisticsChannel::getVolumeParameter, model.getVolumeParameter())
      .set(LogisticsChannel::getSplitCalculation, model.getSplitCalculation())
      .set(LogisticsChannel::getMinWeight, model.getMinWeight())
      .set(LogisticsChannel::getBillingRules, model.getBillingRules())
      .set(LogisticsChannel::getSubstrateParam, model.getSubstrateParam())
      .set(LogisticsChannel::getSplitCalc, model.getSplitCalc())
      .set(LogisticsChannel::getTicketMinWeight, model.getTicketMinWeight())
      .set(
        LogisticsChannel::getTicketMinWeightUnit,
        model.getTicketMinWeightUnit()
      )
      .eq(LogisticsChannel::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(LogisticsChannelSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 运费规则(freightRules) 对应的对象
    LogisticsChannelFreightSearchParamPo freightRulesSearchParam =
      new LogisticsChannelFreightSearchParamPo();
    freightRulesSearchParam.setDisableDataPremissions(true);
    freightRulesSearchParam.setParentLogisticsChannelInList(ids);
    LogisticsChannelFreightMapper localLogisticsChannelFreightMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(LogisticsChannelFreightMapper.class);
    freightRulesSearchParam.applySqlSegments();
    List<Long> freightRulesIdList =
      localLogisticsChannelFreightMapper.searchIds(freightRulesSearchParam);
    if (!freightRulesIdList.isEmpty()) {
      LogisticsChannelFreightService localLogisticsChannelFreightService =
        ContextHolder
          .getApplicationContext()
          .getBean(LogisticsChannelFreightService.class);
      localLogisticsChannelFreightService.batchDelete(freightRulesIdList);
    }

    // 处理子表字段 其他费用(otherExpenses) 对应的对象
    LogisticsChannelOtherFeesSearchParamPo otherExpensesSearchParam =
      new LogisticsChannelOtherFeesSearchParamPo();
    otherExpensesSearchParam.setDisableDataPremissions(true);
    otherExpensesSearchParam.setParentLogisticsChannelInList(ids);
    LogisticsChannelOtherFeesMapper localLogisticsChannelOtherFeesMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(LogisticsChannelOtherFeesMapper.class);
    otherExpensesSearchParam.applySqlSegments();
    List<Long> otherExpensesIdList =
      localLogisticsChannelOtherFeesMapper.searchIds(otherExpensesSearchParam);
    if (!otherExpensesIdList.isEmpty()) {
      LogisticsChannelOtherFeesService localLogisticsChannelOtherFeesService =
        ContextHolder
          .getApplicationContext()
          .getBean(LogisticsChannelOtherFeesService.class);
      localLogisticsChannelOtherFeesService.batchDelete(otherExpensesIdList);
    }
  }

  /**
   * 删除物流渠道
   * @param id 物流渠道的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除物流渠道
   * @param ids 物流渠道的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<LogisticsChannelImportPo> excelToImportRow(
    LogisticsChannelImportPo row,
    Integer rowNumber,
    LogisticsChannelVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<LogisticsChannelImportPo> ir =
      new ImportRow<LogisticsChannelImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<LogisticsChannelImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new LogisticsChannelVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, LogisticsChannelImportPo.class);

    // 一般数据处理
    vo.setExpectAgeing(SheetUtils.tryToInteger(row.getExpectAgeing()));
    if (StringUtils.hasText(row.getModeShipping())) {
      vo.setModeShipping(
        LogisticsChannelModeShippingEnums.toValue(row.getModeShipping())
      );
      if (vo.getModeShipping() == null) {
        ir.addError("modeShipping", "运输方式只能是：“海派”, “空派”");
      }
    }
    if (StringUtils.hasText(row.getTaxIncluded())) {
      vo.setTaxIncluded(
        LogisticsChannelTaxIncludedEnums.toValue(row.getTaxIncluded())
      );
      if (vo.getTaxIncluded() == null) {
        ir.addError("taxIncluded", "是否包税只能是：“是”, “否”");
      }
    }
    if (StringUtils.hasText(row.getState())) {
      vo.setState(LogisticsChannelStateEnums.toValue(row.getState()));
      if (vo.getState() == null) {
        ir.addError("state", "状态只能是：“启用”, “禁用”");
      }
    }
    if (StringUtils.hasText(row.getBllingRules())) {
      vo.setBllingRules(
        LogisticsChannelBllingRulesEnums.toValue(row.getBllingRules())
      );
      if (vo.getBllingRules() == null) {
        ir.addError(
          "bllingRules",
          "计费规则只能是：“计费重(KG)”, “实重(KG)”, “体积(KG)”"
        );
      }
    }
    if (StringUtils.hasText(row.getSplitCalculation())) {
      vo.setSplitCalculation(
        LogisticsChannelSplitCalculationEnums.toValue(row.getSplitCalculation())
      );
      if (vo.getSplitCalculation() == null) {
        ir.addError("splitCalculation", "分抛计算只能是：“是”, “否”");
      }
    }
    vo.setMinWeight(SheetUtils.tryToInteger(row.getMinWeight()));
    if (StringUtils.hasText(row.getBillingRules())) {
      List<SysDictAllItem> billingRulesItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "billingRules",
          n -> sysDictService.getDictItems("SCM00112")
        );
      LogisticsChannelVo finalVo = vo;
      billingRulesItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getBillingRules()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setBillingRules(i.getItemValue()),
          () ->
            ir.addError(
              "billingRules",
              String.format(
                "必须为 %s 中之一",
                billingRulesItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setSubstrateParam(SheetUtils.tryToInteger(row.getSubstrateParam()));
    if (StringUtils.hasText(row.getSplitCalc())) {
      List<SysDictAllItem> splitCalcItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "splitCalc",
          n -> sysDictService.getDictItems("SCM00008")
        );
      LogisticsChannelVo finalVo = vo;
      splitCalcItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getSplitCalc()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setSplitCalc(i.getItemValue()),
          () ->
            ir.addError(
              "splitCalc",
              String.format(
                "必须为 %s 中之一",
                splitCalcItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setTicketMinWeight(SheetUtils.tryToInteger(row.getTicketMinWeight()));
    if (StringUtils.hasText(row.getTicketMinWeightUnit())) {
      List<SysDictAllItem> ticketMinWeightUnitItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "ticketMinWeightUnit",
          n -> sysDictService.getDictItems("SCM00113")
        );
      LogisticsChannelVo finalVo = vo;
      ticketMinWeightUnitItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getTicketMinWeightUnit()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setTicketMinWeightUnit(i.getItemValue()),
          () ->
            ir.addError(
              "ticketMinWeightUnit",
              String.format(
                "必须为 %s 中之一",
                ticketMinWeightUnitItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    // 处理关联字段“物流商”
    if (
      !SheetUtils.isBlank(row.getChannelNameName()) &&
      SheetUtils.isBlank(row.getChannelName())
    ) {
      LogisticsProviderSearchParamPo channelNameSearchParam =
        new LogisticsProviderSearchParamPo();
      channelNameSearchParam.setLimit(2); // 最大只返回二行记录
      channelNameSearchParam.setNameEq(
        SheetUtils.trim(row.getChannelNameName())
      );
      channelNameSearchParam.applySqlSegments();
      List<LogisticsProviderItemVo> channelNameMatches =
        logisticsProviderMapper.search(channelNameSearchParam);
      if (channelNameMatches.size() == 0) {
        ir.addError("channelNameName", "未能在物流商中找到匹配的数据");
      } else if (channelNameMatches.size() > 1) {
        ir.addError(
          "channelNameName",
          "关联不唯一，在物流商中找到多个匹配的数据"
        );
      } else {
        vo.setChannelName(channelNameMatches.get(0).getId());
      }
    }
    // 处理关联字段“目的国家”
    if (
      !SheetUtils.isBlank(row.getDestinationCountryCountry()) &&
      SheetUtils.isBlank(row.getDestinationCountry())
    ) {
      SysCountrySearchParamPo destinationCountrySearchParam =
        new SysCountrySearchParamPo();
      destinationCountrySearchParam.setLimit(2); // 最大只返回二行记录
      destinationCountrySearchParam.setCountryEq(
        SheetUtils.trim(row.getDestinationCountryCountry())
      );
      destinationCountrySearchParam.applySqlSegments();
      List<SysCountryItemVo> destinationCountryMatches =
        sysCountryMapper.search(destinationCountrySearchParam);
      if (destinationCountryMatches.size() == 0) {
        ir.addError("destinationCountryCountry", "未能在国家中找到匹配的数据");
      } else if (destinationCountryMatches.size() > 1) {
        ir.addError(
          "destinationCountryCountry",
          "关联不唯一，在国家中找到多个匹配的数据"
        );
      } else {
        vo.setDestinationCountry(
          destinationCountryMatches
            .stream()
            .map(SysCountryItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“提货地址”
    if (
      !SheetUtils.isBlank(row.getDeliveryAddressName()) &&
      SheetUtils.isBlank(row.getDeliveryAddress())
    ) {
      SysAreaSearchParamPo deliveryAddressSearchParam =
        new SysAreaSearchParamPo();
      deliveryAddressSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryAddressSearchParam.setNameEq(
        SheetUtils.trim(row.getDeliveryAddressName())
      );
      deliveryAddressSearchParam.setFinalFilters(new ArrayList<>());
      deliveryAddressSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("type"))
            .setOp("lt")
            .setValue("3")
        );
      deliveryAddressSearchParam.applySqlSegments();
      List<SysArea> deliveryAddressMatches = sysAreaMapper.search(
        deliveryAddressSearchParam
      );
      if (deliveryAddressMatches.size() == 0) {
        ir.addError("deliveryAddressName", "未能在地区中找到匹配的数据");
      } else if (deliveryAddressMatches.size() > 1) {
        ir.addError(
          "deliveryAddressName",
          "关联不唯一，在地区中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryAddress(deliveryAddressMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<LogisticsChannelImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<LogisticsChannelImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            LogisticsChannelImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              LogisticsChannelImportPo row,
              AnalysisContext cxt
            ) {
              LogisticsChannelVo vo = new LogisticsChannelVo();
              ImportRow<LogisticsChannelImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<LogisticsChannelImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<LogisticsChannelImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      LogisticsChannelVo vo = new LogisticsChannelVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    LogisticsChannelSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "destinationCountry",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((LogisticsChannelItemVo) r).getDestinationCountryCountry()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "deliveryAddress",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((LogisticsChannelItemVo) r).getDeliveryAddressName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "taxIncluded",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            LogisticsChannelTaxIncludedEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "bllingRules",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            LogisticsChannelBllingRulesEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "splitCalculation",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            LogisticsChannelSplitCalculationEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "billingRules",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00112")
      );
      exportOptions.addFieldMappingOption(
        "splitCalc",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00008")
      );
      exportOptions.addFieldMappingOption(
        "ticketMinWeightUnit",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00113")
      );
      exportOptions.addStringFields(
        "name",
        "destinationCountryCountry",
        "deliveryAddressName",
        "taxIncluded",
        "remarks",
        "bllingRules",
        "splitCalculation",
        "billingRules",
        "splitCalc",
        "ticketMinWeightUnit"
      );

      String fileName = String.format(
        "物流渠道(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> billingRulesItems = sysDictService.getDictItems(
      "SCM00112"
    );
    List<SysDictAllItem> splitCalcItems = sysDictService.getDictItems(
      "SCM00008"
    );
    List<SysDictAllItem> ticketMinWeightUnitItems = sysDictService.getDictItems(
      "SCM00113"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<LogisticsChannelExcelPo> items =
      new ArrayList<LogisticsChannelExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<LogisticsChannelItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<LogisticsChannelItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (LogisticsChannelItemVo item : list) {
        LogisticsChannelExcelPo excel = new LogisticsChannelExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setTaxIncluded(
          LogisticsChannelTaxIncludedEnums.toLabel(item.getTaxIncluded())
        );
        excel.setBllingRules(
          LogisticsChannelBllingRulesEnums.toLabel(item.getBllingRules())
        );
        excel.setSplitCalculation(
          LogisticsChannelSplitCalculationEnums.toLabel(
            item.getSplitCalculation()
          )
        );
        if (item.getBillingRules() != null) {
          billingRulesItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getBillingRules()))
            .findFirst()
            .ifPresent(i -> excel.setBillingRules(i.getItemText()));
        }
        if (item.getSplitCalc() != null) {
          splitCalcItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getSplitCalc()))
            .findFirst()
            .ifPresent(i -> excel.setSplitCalc(i.getItemText()));
        }
        if (item.getTicketMinWeightUnit() != null) {
          ticketMinWeightUnitItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getTicketMinWeightUnit()))
            .findFirst()
            .ifPresent(i -> excel.setTicketMinWeightUnit(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "物流渠道(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(LogisticsChannelExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过物流渠道查询物流渠道主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByName(String name) {
    return this.baseMapper.getIdByName(name);
  }

  /**
   * 通过物流渠道查询物流渠道多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByName(List<String> list) {
    return this.baseMapper.getIdsByName(list);
  }

  /**
   * 通过物流渠道主键查询物流渠道
   */
  @Override
  public String getNameById(Long id) {
    return this.baseMapper.getNameById(id);
  }

  /**
   * 通过物流渠道主键查询物流渠道列表
   */
  @Override
  public List<String> getNameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getNameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("name"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 物流渠道的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public LogisticsChannelVo getVoById(Long id) throws Exception {
    LogisticsChannelVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    LogisticsChannelFreightSearchParamPo freightRulesSearchParamPo =
      new LogisticsChannelFreightSearchParamPo();
    freightRulesSearchParamPo.setParentLogisticsChannel(id);
    freightRulesSearchParamPo.getExtendData().put("queryMode", "sub");
    freightRulesSearchParamPo
      .getExtendData()
      .put("queryParent", "LogisticsChannel");
    freightRulesSearchParamPo.applySqlSegments();
    vo.setFreightRules(
      logisticsChannelFreightService.search(freightRulesSearchParamPo)
    );

    LogisticsChannelOtherFeesSearchParamPo otherExpensesSearchParamPo =
      new LogisticsChannelOtherFeesSearchParamPo();
    otherExpensesSearchParamPo.setParentLogisticsChannel(id);
    otherExpensesSearchParamPo.getExtendData().put("queryMode", "sub");
    otherExpensesSearchParamPo
      .getExtendData()
      .put("queryParent", "LogisticsChannel");
    otherExpensesSearchParamPo.applySqlSegments();
    vo.setOtherExpenses(
      logisticsChannelOtherFeesService.search(otherExpensesSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询物流渠道
   * @param search 查询条件
   * @return 物流渠道分页查询结果
   */
  @Override
  public Page<LogisticsChannelItemVo> pageSearch(
    LogisticsChannelSearchParamPo search
  ) {
    Page<LogisticsChannelItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(LogisticsChannelItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 物流渠道快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'LogisticsChannelOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<LogisticsChannelItemVo>> searchOptions(
    LogisticsChannelSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询物流渠道
   * @param search 查询条件
   * @return 物流渠道列表查询结果
   */
  @Override
  public List<LogisticsChannelItemVo> search(
    LogisticsChannelSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询物流渠道最后更新时间
   * @param search 查询条件
   * @return 物流渠道最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(LogisticsChannelSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
